package cn.cy.service.imp;


import cn.cy.core.AiFaceObject;
import cn.cy.core.FaceCompare;
import cn.cy.domain.DTO.ResultDTO;
import cn.cy.domain.Image;
import cn.cy.domain.Result;
import cn.cy.domain.Student;
import cn.cy.service.FaceMatch;
import cn.cy.service.GetStuInfo;
import com.baidu.aip.face.AipFace;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.servlet.http.HttpServletRequest;


@Slf4j
@Service
public class FaceMatchImp implements FaceMatch {
    @Autowired
    AiFaceObject aiFaceObject;
    @Autowired
    FaceCompare faceCompare;
    @Autowired
    GetStuInfo getStuInfo;


    @Override
    public ResultDTO matchface(@Validated Image image) {
        Student student = getStuInfo.getstudent();
        Image image1 = student.getImg();
        JSONObject result = match(image,image1);
        Result resultdata  = new Result();
        int error_code= result.getInt("error_code");

        if(error_code == 0){

            System.out.println(result.getJSONObject("result"));
            JSONObject resultlist = result.getJSONObject("result");
            double score = resultlist.getDouble("score");
            if(score>80)
            {
                resultdata.setStart(true);
                resultdata.setMsg("对比成功");
                ResultDTO<Result> resultResultDTO = new ResultDTO<Result>("success",resultdata);
                return resultResultDTO;
            }
        }
        else {
            System.out.println(error_code);
        }
        return new ResultDTO("fail");

    }

    private JSONObject match(Image image1, Image image2){
        AipFace client = aiFaceObject.getClient();
        String res = faceCompare.facematch(client,image1,image2);
        JSONObject result = new JSONObject(res);
        return  result;
    }
}
